import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth'

class WebSocketClient {
  constructor() {
    this.ws = null
    this.url = import.meta.env.VITE_WS_URL || 'ws://localhost:8080/ws'
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 3000
    this.heartbeatInterval = 30000
    this.heartbeatTimer = null
    this.messageHandlers = new Set()
    this.isConnected = false
  }

  // 连接WebSocket
  connect() {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) return

    const token = getToken()
    this.ws = new WebSocket(`${this.url}?token=${token}`)

    this.ws.onopen = () => {
      console.log('WebSocket连接成功')
      this.isConnected = true
      this.reconnectAttempts = 0
      this.startHeartbeat()
      this.notifyHandlers({ type: 'system', content: '连接成功' })
    }

    this.ws.onclose = () => {
      console.log('WebSocket连接关闭')
      this.isConnected = false
      this.stopHeartbeat()
      this.reconnect()
    }

    this.ws.onerror = (error) => {
      console.error('WebSocket错误:', error)
      this.notifyHandlers({ type: 'error', content: '连接错误' })
    }

    this.ws.onmessage = (event) => {
      try {
        const message = JSON.parse(event.data)
        this.handleMessage(message)
      } catch (error) {
        console.error('消息解析错误:', error)
      }
    }
  }

  // 重连机制
  reconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.log('达到最大重连次数')
      this.notifyHandlers({ type: 'error', content: '连接已断开，请刷新页面重试' })
      return
    }

    this.reconnectAttempts++
    console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
    
    setTimeout(() => {
      this.connect()
    }, this.reconnectInterval)
  }

  // 心跳检测
  startHeartbeat() {
    this.heartbeatTimer = setInterval(() => {
      if (this.isConnected) {
        this.send({ type: 'heartbeat' })
      }
    }, this.heartbeatInterval)
  }

  stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer)
      this.heartbeatTimer = null
    }
  }

  // 发送消息
  send(data) {
    if (!this.isConnected) {
      console.warn('WebSocket未连接')
      return
    }
    this.ws.send(JSON.stringify(data))
  }

  // 处理接收到的消息
  handleMessage(message) {
    switch (message.type) {
      case 'notification':
        this.handleNotification(message)
        break
      case 'heartbeat':
        // 心跳响应，不做处理
        break
      default:
        this.notifyHandlers(message)
    }
  }

  // 处理通知消息
  handleNotification(message) {
    // 检查是否在免打扰时间
    const settings = JSON.parse(localStorage.getItem('messageSettings') || '{}')
    const { reminderSettings = {} } = settings
    const { quietTime = [], desktop = true } = reminderSettings

    if (this.isInQuietTime(quietTime)) {
      console.log('当前处于免打扰时间')
      return
    }

    // 显示桌面通知
    if (desktop && Notification.permission === 'granted') {
      this.showDesktopNotification(message)
    }

    // 播放提示音
    if (reminderSettings.sound) {
      this.playNotificationSound()
    }

    // 通知消息处理器
    this.notifyHandlers(message)
  }

  // 显示桌面通知
  showDesktopNotification(message) {
    const notification = new Notification(message.title, {
      body: message.content,
      icon: '/favicon.ico'
    })

    notification.onclick = () => {
      window.focus()
      notification.close()
    }
  }

  // 播放提示音
  playNotificationSound() {
    const audio = new Audio('/notification.mp3')
    audio.play().catch(error => {
      console.error('播放提示音失败:', error)
    })
  }

  // 检查是否在免打扰时间
  isInQuietTime(quietTime) {
    if (!quietTime || !quietTime.length) return false

    const now = new Date()
    const currentTime = now.getHours() * 60 + now.getMinutes()
    const [start, end] = quietTime

    if (!start || !end) return false

    const startTime = start.getHours() * 60 + start.getMinutes()
    const endTime = end.getHours() * 60 + end.getMinutes()

    return currentTime >= startTime && currentTime <= endTime
  }

  // 添加消息处理器
  addMessageHandler(handler) {
    this.messageHandlers.add(handler)
  }

  // 移除消息处理器
  removeMessageHandler(handler) {
    this.messageHandlers.delete(handler)
  }

  // 通知所有消息处理器
  notifyHandlers(message) {
    this.messageHandlers.forEach(handler => {
      try {
        handler(message)
      } catch (error) {
        console.error('消息处理器错误:', error)
      }
    })
  }

  // 关闭连接
  disconnect() {
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
    this.stopHeartbeat()
    this.isConnected = false
  }
}

// 创建单例
const wsClient = new WebSocketClient()

// 请求通知权限
if (Notification.permission === 'default') {
  Notification.requestPermission()
}

export default wsClient 